const fs = require("fs");
const path = require("path");
const Lock = require('async-lock');
const lock = new Lock();

const list = async (ctx) => {
    const { status, start, end } = ctx.request.body;
    const imgsDir = path.resolve(__dirname, "../../selected_pics");
    const folders = await fs.promises.readdir(imgsDir, { withFileTypes: true });
    const result = [];

    const baseURL = `${ctx.protocol}://${ctx.host}`;

    // 按文件夹名称进行排序（数字从小到大）
    const sortedFolders = folders
        .filter(folder => folder.isDirectory())
        .sort((a, b) => parseInt(a.name) - parseInt(b.name));

    // 根据 start 和 end 设置查询范围
    const startIndex = start ? Math.max(0, start - 1) : 0;
    const endIndex = end ? Math.min(end, sortedFolders.length) : sortedFolders.length;

    // 根据 status 过滤文件夹
    const validAngles = ['angle0', 'angle45', 'angle90', 'angle135', 'angle180', 'angle225', 'angle270', 'angle315'];

    let serialNumber = typeof startIndex === 'number' && typeof endIndex === 'number' ? startIndex+1 : 1; // 初始化序列号

    for (const folder of sortedFolders.slice(startIndex, endIndex)) {
        const folderPath = path.join(imgsDir, folder.name);
        const files = await fs.promises.readdir(folderPath);

        const folderData = { 
            id: parseInt(folder.name),
            serialNumber: serialNumber++ // 增加序列号
        };

        // 判断是否有status.json文件
        const statusFilePath = path.join(folderPath, "status.json");
        let folderStatus = null;

        if (fs.existsSync(statusFilePath)) {
            const statusFileContent = await fs.promises.readFile(statusFilePath, "utf-8");
            folderStatus = JSON.parse(statusFileContent);
        }

        // 根据 status 来过滤数据
        let isValid = false;

        if (status === 'all' || !statusFilePath) {
            // 状态是 '全部' 或者没有 status.json 文件
            isValid = true;
        } else if (validAngles.includes(status) && folderStatus && folderStatus.angle === status.replace('angle', '')) {
            // 根据 angle 过滤
            isValid = true;
        } else if (status === 'none' && folderStatus && folderStatus.angle === 'none') {
            // 过滤没有 angle 字段的文件夹
            isValid = true;
        } else if (status === 0 && !folderStatus) {
            // status === '0' 时，过滤没有 status.json 文件的文件夹（待审核）
            isValid = true;
        }

        if (isValid) {
            // 如果文件夹符合条件，获取文件并构建返回数据
            for (const file of files) {
                const fileExt = path.extname(file).toLowerCase();
                if (fileExt === ".png") {
                    const direction = parseInt(path.basename(file, fileExt).substring(1), 10);
                    console.log(direction)
                    const accessiblePath = `${baseURL}/${folder.name}/${file}`;
                    folderData[direction] = accessiblePath;
                }
            }

            // 如果有 status.json 文件，则把它的内容加入返回数据
            if (folderStatus) {
                folderData.status = folderStatus;
            }

            if (Object.keys(folderData).length > 1) { 
                result.push(folderData);
            }
        }
    }

    // 按照文件夹id排序
    result.sort((a, b) => a.id - b.id);

    ctx.body = result;
};




// 格式化时间函数
const formatTime = (date) => {
    const pad = (num) => String(num).padStart(2, "0");
    return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` +
           `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
};



const saveStatus = async (ctx) => {
    const { id, data } = ctx.request.body;

    if (!id || !data || typeof id !== "number") {
        ctx.status = 400;
        ctx.body = { error: "Invalid id or data" };
        return;
    }

    const folderPath = path.resolve(__dirname, `../../selected_pics/${id}`);
    const statusFilePath = path.join(folderPath, "status.json");

    try {
        if (!fs.existsSync(folderPath)) {
            ctx.status = 404;
            ctx.body = { error: "Folder not found" };
            return;
        }

        await lock.acquire(`status-${id}`, async () => { // 加锁
            const currentTime = formatTime(new Date());
            let fileData = {};

            if (fs.existsSync(statusFilePath)) {
                const existingContent = await fs.promises.readFile(statusFilePath, "utf-8");
                fileData = JSON.parse(existingContent);
                fileData.updatedAt = currentTime;
            } else {
                fileData.createdAt = currentTime;
                fileData.updatedAt = currentTime;
            }

            fileData = { ...fileData, ...data };
            await fs.promises.writeFile(statusFilePath, JSON.stringify(fileData, null, 2));
        });

        ctx.body = { message: "Status saved successfully", status: 'ok' };
    } catch (error) {
        console.error("Error saving status:", error);
        ctx.status = 500;
        ctx.body = { error: "Internal server error" };
    }
};
const getStatistics = async (ctx) => {
    const imgsDir = path.resolve(__dirname, "../../selected_pics");
    const folders = await fs.promises.readdir(imgsDir, { withFileTypes: true });

    // 统计数据初始化
    let reviewedCount = 0;
    let unreviewedCount = 0;
    let angleCount = {};

    for (const folder of folders) {
        if (folder.isDirectory()) {
            const folderPath = path.join(imgsDir, folder.name);
            const files = await fs.promises.readdir(folderPath);
            let hasStatusFile = false;
            
            // 遍历文件夹中的文件，统计文件数和查看是否有 status.json 文件
            for (const file of files) {
                if (file === "status.json") {
                    hasStatusFile = true; // 该文件夹有 status.json 文件
                }
            }

            if (hasStatusFile) {
                reviewedCount++; // 已审核文件夹数量
                // 读取 status.json 文件
                const statusFilePath = path.join(folderPath, "status.json");
                try {
                    const statusFileContent = await fs.promises.readFile(statusFilePath, "utf-8");
                    const statusData = JSON.parse(statusFileContent);
                    // 如果 status.json 中有 angle 字段，统计其数量
                    if (statusData.angle) {
                        angleCount[statusData.angle] = (angleCount[statusData.angle] || 0) + 1;
                    }
                } catch (error) {
                    console.error(`Error reading status.json for folder ${folder.name}:`, error);
                }
            } else {
                unreviewedCount++; // 未审核文件夹数量
            }
        }
    }

    // 返回统计数据
    ctx.body = {
        reviewedCount,
        unreviewedCount,
        angleCount
    };
};
module.exports = {
    list,
    saveStatus,
    getStatistics
};
